﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.CycleTimeReport.CApCTRMgr
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Forms;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Olp;
using Tecnomatix.Engineering.Olp.PrivateImplementationDetails;


namespace DnProcessSimulateCommands.CycleTimeReport;

internal class CApCTRMgr
{
  private CApCTRToggleCmd m_cmd;
  private bool m_registeredForActiveDocumentUnloadingEvent;
  private bool m_registeredForSimulationEvents;
  private bool m_autoTestRun;
  private string m_autoTestPath;
  private double m_totalSimTime;
  private TxOlpControllerUtilities m_ctrollerUtilities = new TxOlpControllerUtilities();

  public bool AutoTestRun
  {
    get => this.m_autoTestRun;
    set => this.m_autoTestRun = value;
  }

  public string AutoTestPath
  {
    get => this.m_autoTestPath;
    set => this.m_autoTestPath = value;
  }

  public CApCTRExcelExporter ExcelExporter { get; private set; }

  internal CApCTRMgr(CApCTRToggleCmd cmd) => this.m_cmd = cmd;

  public void ClearTimerSettings()
  {
    TxOlpRoboticSimulationEventsManager.Instance.ClearTimerSettings();
  }

  public void AddTimerSetting(string originalTimerName, TxOlpCTRSettingsTimerInfo setting)
  {
    TxOlpRoboticSimulationEventsManager.Instance.AddTimerSetting(originalTimerName, setting);
  }

  public void ClearSimulationData()
  {
    TxOlpRoboticSimulationEventsManager.Instance.ClearSimulationEventData();
  }

  public bool IsUserTimersIgnored()
  {
    return TxOlpRoboticSimulationEventsManager.Instance.IgnoreUserTimers;
  }

  public void IgnoreUserTimers(bool ignore)
  {
    TxOlpRoboticSimulationEventsManager.Instance.IgnoreUserTimers = ignore;
  }

  public bool IsTimerPriorityIgnored()
  {
    return TxOlpRoboticSimulationEventsManager.Instance.IgnoreTimerPriority;
  }

  public void IgnoreTimerPriority(bool ignore)
  {
    TxOlpRoboticSimulationEventsManager.Instance.IgnoreTimerPriority = ignore;
  }

  public bool IsEmptyCycleTimeReport()
  {
    return TxOlpRoboticSimulationEventsManager.Instance.SimulationEventData.Count <= 0;
  }

  public bool IsCycleTimeReportActivated()
  {
    return TxOlpRoboticSimulationEventsManager.Instance.CycleTimeReportActive;
  }

  public void ActivateCycleTimeReport(bool activate)
  {
    TxOlpRoboticSimulationEventsManager.Instance.CycleTimeReportActive = activate;
    if (activate)
      this.RegisterEvents();
    else
      this.UnRegisterEvents();
  }

  public void RegisterEvents()
  {
    this.RegisterDocumentEvents();
    this.RegisterSimulationEvents();
  }

  public void UnRegisterEvents()
  {
    this.UnregisterDocumentEvents();
    this.UnRegisterSimulationEvents();
  }

  private void RegisterDocumentEvents()
  {
    this.RegisterDocumentLoadedEvent();
    this.RegisterActiveDocumentUnLoadingEvent();
  }

  private void UnregisterDocumentEvents()
  {
    this.UnRegisterDocumentLoadedEvent();
    this.UnRegisterActiveDocumentUnLoadingEvent();
  }

  private void RegisterDocumentLoadedEvent()
  {
    TxApplication.DocumentCollection.DocumentLoaded += new TxDocumentCollection_DocumentLoadedEventHandler(this.OnLoadDocument);
  }

  private void UnRegisterDocumentLoadedEvent()
  {
    TxApplication.DocumentCollection.DocumentLoaded -= new TxDocumentCollection_DocumentLoadedEventHandler(this.OnLoadDocument);
  }

  private void RegisterActiveDocumentUnLoadingEvent()
  {
    if (this.m_registeredForActiveDocumentUnloadingEvent)
      return;
    TxDocument activeDocument = TxApplication.ActiveDocument;
    if (activeDocument == null || !TxApplication.ActiveDocument.PlatformGlobalServicesProvider.IsDocumentLoaded())
      return;
    activeDocument.Unloading += new TxDocument_UnloadingEventHandler(this.OnUnloadingDocument);
    this.m_registeredForActiveDocumentUnloadingEvent = true;
  }

  private void UnRegisterActiveDocumentUnLoadingEvent()
  {
    if (!this.m_registeredForActiveDocumentUnloadingEvent)
      return;
    this.m_registeredForActiveDocumentUnloadingEvent = false;
    TxDocument activeDocument = TxApplication.ActiveDocument;
    if (activeDocument == null)
      return;
    activeDocument.Unloading -= new TxDocument_UnloadingEventHandler(this.OnUnloadingDocument);
  }

  private void OnLoadDocument(object sender, TxDocumentCollection_DocumentLoadedEventArgs args)
  {
    this.RegisterActiveDocumentUnLoadingEvent();
    this.RegisterSimulationEvents();
  }

  private void OnUnloadingDocument(object sender, TxDocument_UnloadingEventArgs args)
  {
    this.ActivateCycleTimeReport(false);
    if (!this.m_cmd.Pressed)
      return;
    this.m_cmd.Pressed = false;
  }

  private void RegisterSimulationEvents()
  {
    try
    {
      TxDocument activeDocument = TxApplication.ActiveDocument;
      if (activeDocument == null || this.m_registeredForSimulationEvents || !TxApplication.ActiveDocument.PlatformGlobalServicesProvider.IsDocumentLoaded())
        return;
      this.m_registeredForSimulationEvents = true;
      activeDocument.SimulationPlayer.SimulationStopped += new TxSimulationPlayer_SimulationStoppedEventHandler(this.SimulationPlayer_SimulationStopped);
      activeDocument.SimulationPlayer.SimulationEndedForward += new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.SimulationPlayer_SimulationEndedForward);
      activeDocument.SimulationPlayer.SimulationCleared += new TxSimulationPlayer_SimulationClearedEventHandler(this.SimulationPlayer_SimulationCleared);
    }
    catch (Exception ex)
    {
    }
  }

  private void UnRegisterSimulationEvents()
  {
    try
    {
      TxDocument activeDocument = TxApplication.ActiveDocument;
      if (activeDocument == null || !this.m_registeredForSimulationEvents)
        return;
      this.m_registeredForSimulationEvents = false;
      activeDocument.SimulationPlayer.SimulationStopped -= new TxSimulationPlayer_SimulationStoppedEventHandler(this.SimulationPlayer_SimulationStopped);
      activeDocument.SimulationPlayer.SimulationEndedForward -= new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.SimulationPlayer_SimulationEndedForward);
      activeDocument.SimulationPlayer.SimulationCleared -= new TxSimulationPlayer_SimulationClearedEventHandler(this.SimulationPlayer_SimulationCleared);
    }
    catch (Exception ex)
    {
    }
  }

  private void SimulationPlayer_SimulationEndedForward(
    object sender,
    TxSimulationPlayer_SimulationEndedForwardEventArgs e)
  {
    if (!this.IsCycleTimeReportActivated() || !TxApplication.ActiveDocument.SimulationPlayer.RefreshMode)
      return;
    this.m_totalSimTime = TxApplication.ActiveDocument.SimulationPlayer.CurrentTime;
    this.CreateExcelReport();
    if (this.AutoTestRun)
      return;
    this.ClearSimulationData();
  }

  private void SimulationPlayer_SimulationStopped(
    object sender,
    TxSimulationPlayer_SimulationStoppedEventArgs e)
  {
    if (!this.IsCycleTimeReportActivated() || !TxApplication.ActiveDocument.SimulationPlayer.RefreshMode)
      return;
    this.m_totalSimTime = TxApplication.ActiveDocument.SimulationPlayer.CurrentTime;
    this.CreateExcelReport();
    if (this.AutoTestRun)
      return;
    this.ClearSimulationData();
  }

  private void SimulationPlayer_SimulationCleared(
    object sender,
    TxSimulationPlayer_SimulationClearedEventArgs e)
  {
    if (!this.IsCycleTimeReportActivated() || !TxApplication.ActiveDocument.SimulationPlayer.RefreshMode || this.AutoTestRun)
      return;
    this.ClearSimulationData();
  }

  private void CreateExcelReport()
  {
    if (TxOlpRoboticSimulationEventsManager.Instance.SimulationEventData.Count <= 0)
      return;
    Cursor current = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    this.ExcelExporter = new CApCTRExcelExporter();
    if (string.IsNullOrEmpty(this.AutoTestPath))
    {
      if (!TxAssemblyInfoEx.IsExcelInstalled(true, $"\n'{((TxButtonCommand) this.m_cmd).Name}' {CApCTRStringTable.COMMAND_NAME}"))
        return;
      this.ExcelExporter.InitExcel(this.IsTimerPriorityIgnored());
    }
    List<TxOlpCTREventInfo> simulationEventData = TxOlpRoboticSimulationEventsManager.Instance.SimulationEventData;
    Hashtable hashtable = new Hashtable();
    foreach (TxOlpCTREventInfo txOlpCtrEventInfo in simulationEventData)
    {
      if (!TxRobot.op_Equality(txOlpCtrEventInfo.Robot, (ITxObject) null) && !(txOlpCtrEventInfo.EventName == ""))
      {
        string hashKey = this.GetHashKey((object) txOlpCtrEventInfo.Robot);
        if (!hashtable.ContainsKey((object) hashKey))
          hashtable.Add((object) hashKey, (object) new List<TxOlpCTREventInfo>());
        if (txOlpCtrEventInfo is TxOlpCTRTimerEventInfo)
        {
          if (!this.IsUserTimersIgnored())
          {
            if (this.IsTimerPriorityIgnored())
              txOlpCtrEventInfo.Priority = 1;
            ((List<TxOlpCTREventInfo>) hashtable[(object) hashKey]).Add(txOlpCtrEventInfo);
          }
        }
        else if (TxOlpRoboticSimulationEventsManager.Instance.IsTimerActive(txOlpCtrEventInfo.EventName))
        {
          if (this.IsTimerPriorityIgnored() || !TxOlpRoboticSimulationEventsManager.Instance.SupportPriority(txOlpCtrEventInfo.EventName))
          {
            txOlpCtrEventInfo.Priority = 1;
          }
          else
          {
            int? nullable = TxOlpRoboticSimulationEventsManager.Instance.TimerPriority(txOlpCtrEventInfo.EventName);
            if (nullable.HasValue)
              txOlpCtrEventInfo.Priority = nullable.Value;
          }
          ((List<TxOlpCTREventInfo>) hashtable[(object) hashKey]).Add(txOlpCtrEventInfo);
        }
      }
    }
    CApCTREventsCalc capCtrEventsCalc = new CApCTREventsCalc();
    TxOlpCTRSystemEventInfo ctrSystemEventInfo = new TxOlpCTRSystemEventInfo("EndOfSimulation", (TxOlpCTREventStatus) 0, TxApplication.ActiveDocument.SimulationPlayer.CurrentTime);
    StreamWriter streamWriter = (StreamWriter) null;
    if (!string.IsNullOrEmpty(this.AutoTestPath))
    {
      if (File.Exists(this.AutoTestPath))
        File.Delete(this.AutoTestPath);
      streamWriter = File.AppendText(this.AutoTestPath);
    }
    foreach (string key1 in (IEnumerable) hashtable.Keys)
    {
      ((List<TxOlpCTREventInfo>) hashtable[(object) key1]).Add((TxOlpCTREventInfo) ctrSystemEventInfo);
      int cycleNumber;
      string programNumber;
      List<CApCTRTimer> timers = capCtrEventsCalc.Calc(hashtable[(object) key1] as List<TxOlpCTREventInfo>, out cycleNumber, out programNumber);
      if (streamWriter != null)
      {
        foreach (CApCTRTimer capCtrTimer in timers)
        {
          string str = capCtrTimer.ToString();
          if (TxRobot.op_Inequality(capCtrTimer.Robot, (ITxObject) null))
            str = $"{((TxBaseGeometryCreationObject) capCtrTimer.Robot).Name} {str}";
          streamWriter.WriteLine(str);
        }
        Dictionary<string, double> timerTotals = new Dictionary<string, double>();
        double totalOfAllTimers = 0.0;
        this.ExcelExporter.GetTimerNamesAndTotals(timers, timerTotals, ref totalOfAllTimers);
        foreach (string key2 in timerTotals.Keys)
        {
          string str1 = CApCTRUtilities.DoubleToString(timerTotals[key2], "f3", true);
          string str2 = $"{key2} {str1}";
          if (TxRobot.op_Inequality(timers[0].Robot, (ITxObject) null))
            str2 = $"{((TxBaseGeometryCreationObject) timers[0].Robot).Name} {str2}";
          streamWriter.WriteLine(str2);
        }
      }
      if (streamWriter == null && timers.Count > 0)
        this.ExcelExporter.CreateExcelSheetForOneRobotOrCompound(key1, timers, cycleNumber, programNumber);
      capCtrEventsCalc.Clear();
    }
    if (streamWriter != null)
      streamWriter.Close();
    else
      this.ExcelExporter.CreateExcelSheetForTimerSettings();
    if (!this.AutoTestRun)
      this.ExcelExporter.ShowExcel();
    Cursor.Current = current;
  }

  private void SummarizeTimeTotals(
    List<TxOlpCTREventInfo> eventDataList,
    ref double totalWeldTime,
    ref double totalMotionTime)
  {
    totalWeldTime = 0.0;
    totalMotionTime = 0.0;
    double num = 0.0;
    foreach (TxOlpCTREventInfo eventData in eventDataList)
    {
      if (eventData.EventName == "MotionToLocation" && eventData.Status == 1)
        num = eventData.EventTime;
      else if (eventData.EventName == "MotionToLocation" && eventData.Status == null)
        totalMotionTime += eventData.EventTime - num;
    }
  }

  private string GetHashKey(object robotId)
  {
    string id = ((TxBaseGeometryCreationObject) (robotId as TxRobot)).Id;
    if (robotId is TxRobot && ((TxBaseGeometryCreationObject) (robotId as TxRobot)).Collection != null)
    {
      ITxObjectCollection collection = ((TxBaseGeometryCreationObject) (robotId as TxRobot)).Collection;
      if (collection is ITxComponent && (collection as ITxComponent).IsEquipment && ((Collection<ITxObject>) ((ITxObject) collection).Collection.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (TxRobot)))).Count > 1)
        id = ((ITxObject) collection).Id;
    }
    return id;
  }
}
